package dhz.tools.popup.actions;

import java.io.File;

import org.apache.log4j.Logger;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import dhz.tools.dialog.GzipDialog;
import dhz.tools.service.GzipService;
/**
 * GZIP压缩
 * @author dhz
 */
public class GzipAction implements IObjectActionDelegate {

	private static final Logger LOG = Logger.getLogger(GzipAction.class);
	
	private Shell shell;
	private ISelection selection;
	
	public GzipAction() {
		super();
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	public void run(IAction action) {
		StructuredSelection sel = (StructuredSelection)selection;
		IResource resource = (IResource)sel.getFirstElement();
		
		GzipDialog dialog = new GzipDialog(shell);
		int result = dialog.open();
		if(result == IDialogConstants.OK_ID){
			File file = resource.getLocation().toFile();
			try {
				new GzipService().gzipFile(shell,file,dialog.getGzipStr(),dialog.getNameTexts(),
						dialog.getType(),dialog.getSizeFromVal(),dialog.getSizeToVal());
				//刷新exporer
				resource.getParent().refreshLocal(IResource.DEPTH_INFINITE,null);
			} catch (Exception e) {
				LOG.error("GZIP压缩时出错",e);
				MessageDialog.openError(shell,"错误",e.getMessage());
			}
		}
	}

	public void selectionChanged(IAction action, ISelection selection) {
		this.selection  = selection;
	}

}
